package io.basic.char_;

import org.junit.Test;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriter_ {
    /**
     * 按一个字符写入
     */
    @Test
    public void test1() {
        String filePath = "/Users/tomdayu/home/hello3.txt";
        int readData = 0;
        FileWriter writer = null;
        char[] chars = {'a','b','c'};
        try {
            //创建流对象，用于读取文件
            writer = new FileWriter(filePath);
            writer.write("H");
            writer.write("Hggg",0, 2);
            writer.write(chars);
//            writer.write(chars, 0, 4);
            writer.write("许诗雅大笨蛋".toCharArray(), 0, 6);
            //数据量大用循环

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 优化速率 一次读多个字节
     */
    @Test
    public void readFile02() {
        String filePath = "/Users/tomdayu/home/hello.txt";
        int readLen = 0;
        char[] buf = new char[14];
        FileReader in = null;
        try {
            //创建流对象，用于读取文件
            in = new FileReader(filePath);
            //从流中读取多个字节到字节数组buf
            //返回实际读取的字节数
            while ((readLen = in.read(buf)) != -1) {
                System.out.println(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
